package com.shujia.wyh.day21;

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/*
        HashMap<Student,String>
 */
public class TreeMapDemo2 {
    public static void main(String[] args) {
        //创建集合对象
        //自然排序
//        TreeMap<Student4, String> map = new TreeMap<>();
        //比较器排序
//        TreeMap<Student4, String> map = new TreeMap<>(new MyComparator());
        //匿名内部类实现比较器排序
        TreeMap<Student4, String> map = new TreeMap<>(new Comparator<Student4>() {
            @Override
            public int compare(Student4 o1, Student4 o2) {
                int i = o1.getName().compareTo(o2.getName());
                //姓名一样，年龄不一定一样
                int i2 = (i == 0) ? o1.getAge() - o2.getAge() : i;
                return i2;
            }
        });


        //创建学生对象
        Student4 s1 = new Student4("张三", 18);
        Student4 s2 = new Student4("李四", 19);
        Student4 s3 = new Student4("王五", 17);
        Student4 s4 = new Student4("赵六", 81);
        Student4 s5 = new Student4("张三", 18);

        //向集合中添加元素
        map.put(s1, "aaaa");
        map.put(s2, "bbbb");
        map.put(s3, "cccc");
        map.put(s4, "dddd");
        map.put(s5, "eeee");

        //遍历集合
        Set<Map.Entry<Student4, String>> entries = map.entrySet();
        for (Map.Entry<Student4, String> keyValue : entries) {
            Student4 key = keyValue.getKey();
            String value = keyValue.getValue();
            System.out.println(key + ":" + value);
        }
    }
}
